package com.cloudservice.ccs.biz.impl;

import com.cloudservice.ccs.biz.ICustomerServiceDesignationBiz;
import com.cloudservice.ccs.biz.ISessionBiz;
import com.cloudservice.ccs.entity.CustomerService;
import com.cloudservice.ccs.entity.Session;
import com.cloudservice.ccs.entity.VisitorInfo;
import com.cloudservice.ccs.exception.CustomerServiceDesignationException;
import com.cloudservice.ccs.mapper.CustomerServiceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CustomerServiceDesignationImpl implements ICustomerServiceDesignationBiz {

    @Autowired
    ISessionBiz sessionBiz;

    @Autowired
    CustomerServiceMapper customerServiceMapper;

    @Override
    public Integer designateCustomerService(VisitorInfo visitorInfo) {
        Map<String, Object> conditions = new HashMap<>(1);
        conditions.put("state", "在线");
        List<CustomerService> onlineCustomerService = customerServiceMapper.getWithConditions(conditions);
        if (onlineCustomerService.isEmpty()) {
            throw new CustomerServiceDesignationException("当前没有在线的客服");
        } else {
            return onlineCustomerService.get(0).getCustomerServiceId();
        }
    }

    @Override
    public Session getSession(VisitorInfo visitorInfo) {
        Integer customerServiceId = designateCustomerService(visitorInfo);
        Session session = new Session();
        session.setCustomerServiceId(customerServiceId);
        session.setVisitorIp(visitorInfo.getIp());
        session.setVisiterName(visitorInfo.getVisitorName());
        return session;
    }

    @Override
    public Integer createSession(VisitorInfo visitorInfo) {
        Session session = sessionBiz.getAvailableSession(visitorInfo.getIp());
        if (session == null) {
            session = getSession(visitorInfo);
            sessionBiz.save(session);
        } else {
            session.setActive(true);
            sessionBiz.update(session.getSessionId(), session);
        }
        visitorInfo.setCustomerServiceId(session.getCustomerServiceId());
        return session.getSessionId();
    }
}
